package org.atlantis.ymer.server;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class FlashPolicyHandler extends SimpleChannelUpstreamHandler {

	private static final Logger log = LoggerFactory.getLogger(FlashPolicyHandler.class);

	private static final String NEWLINE = "\r\n";

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		ChannelFuture f = e.getChannel().write(this.getPolicyFileContents());
		f.addListener(ChannelFutureListener.CLOSE);
	}

	private ChannelBuffer getPolicyFileContents() throws Exception {
		return ChannelBuffers.copiedBuffer("<?xml version=\"1.0\"?>" + NEWLINE
				+ "<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">" + NEWLINE
				+ "<cross-domain-policy> " + NEWLINE + "   <site-control permitted-cross-domain-policies=\"master-only\"/>"
				+ NEWLINE + "   <allow-access-from domain=\"*\" to-ports=\"*\" />" + NEWLINE + "</cross-domain-policy>"
				+ NEWLINE, CharsetUtil.UTF_8);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		ctx.getChannel().close();
		log.error("Flash policy server response error.", e.getCause());
	}
}
